<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button @click="showdialogVisible" type="primary">添加分类</el-button>
        </el-col>
      </el-row>
      <!--main.js中引用的树形组件-->
      <tree-table :columns="columns" :data="tableData" :expand-type="false" :selection-type="false"
                  class="tree-table1" index-text="#" show-index>
        <!--是否有效-->
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-success" style="color: lightgreen" v-if="scope.row.cat_deleted === false"></i>
          <i class="el-icon-error" style="color: red" v-else></i>
        </template>
        <!--排序-->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag size="mini" type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag size="mini" type="warn" v-else>三级</el-tag>
        </template>
        <!--操作-->
        <template slot="opt">
          <el-button icon="el-icon-edit" size="mini" type="primary">编辑</el-button>
          <el-button icon="el-icon-delete" size="mini" type="danger">删除</el-button>
        </template>
      </tree-table>
      <!--   分页   -->
      <el-pagination
        :current-page="queryInfo.pagenum"
        :page-size="queryInfo.pagesize"
        :page-sizes="[1, 2, 5, 10]"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </el-card>
    <!--添加用户的对话框-->
    <el-dialog
      :visible.sync="dialogVisible"
      @close="addDialogClosed('addFormRef')"
      title="添加分类"
      width="50%">
      <el-form :model="addForm" :rules="addFormRules" label-width="100px" ref="addFormRef">
        <el-form-item label="*分类名称：" prop="cat_name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：" prop="password">
          <el-cascader
            :options="parentCatList"
            :props="cascaderProps"
            @change="handleChange"
            change-on-select
            clearable expand-change="hover"
            v-model="selectedKeys"></el-cascader>
        </el-form-item>
      </el-form>
      <span class="dialog-footer" slot="footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button @click="addCate('addFormRef')" type="primary">确 定</el-button>
  </span>
    </el-dialog>

    <!--修改用户的对话框-->
    <el-dialog
      :visible.sync="editdialogVisible"
      @close="editDialogClosed('editFormRef')"
      title="修改用户"
      width="50%">
      <el-form :model="editForm" :rules="editFormRules" label-width="70px" ref="editFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input :disabled="true" v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span class="dialog-footer" slot="footer">
    <el-button @click="editdialogVisible = false">取 消</el-button>
    <el-button @click="editUser('editFormRef')" type="primary">确 定</el-button>
  </span>
    </el-dialog>
    <!--分配角色的对话框-->
    <el-dialog
      :visible.sync="setRoledialogVisible"
      @close="setRoleDialogClosed('setRoleFormRef')"
      title="分配角色"
      width="50%">
      <el-form :model="setRoleForm" ref="setRoleFormRef">
        <el-form-item label="当前用户：" prop="username">
          <span>{{setRoleForm.username}}</span>
        </el-form-item>
        <el-form-item label="当前角色：" prop="role">
          <span>{{setRoleForm.role_name}}</span>
        </el-form-item>
        <el-form-item label="分配新角色：" prop="role">
          <el-select placeholder="请选择" v-model="selectedRoleId">
            <el-option
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
              v-for="item in roleNameList">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span class="dialog-footer" slot="footer">
    <el-button @click="setRoledialogVisible = false">取 消</el-button>
    <el-button @click="saveRole('setRoleFormRef')" type="primary">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable */
export default {
  name: 'user',
  data () {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.addForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    const checkphone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else if (!this.isCellPhone(value)) {
        callback(new Error('请输入正确的手机号!'))
      } else {
        callback()
      }
    }
    return {
      queryInfo: {
        type: '3',
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      tableData: [],
      total: 0,
      columns: [{
        label: '分类名称',
        prop: 'cat_name'
      }, {
        label: '是否有效',
        type: 'template',
        template: 'isok'
      }, {
        label: '排序',
        type: 'template',
        template: 'order'
      }, {
        label: '操作',
        type: 'template',
        template: 'opt'
      }],
      dialogVisible: false,
      editdialogVisible: false,
      setRoledialogVisible: false,
      addForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0
      },
      editForm: {
        id: '',
        email: '',
        mobile: ''
      },
      setRoleForm: {
        id: '',
        username: '',
        role_name: ''
      },
      addFormRules: {
        name: [
          {
            required: true,
            message: '请输入分类名称',
            trigger: 'blur'
          }
        ]
      },
      editFormRules: {},
      roleNameList: [],
      selectedRoleId: '',
      parentCatList: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      selectedKeys: []
    }
  },
  created () {
    this.gettableData()
  },
  methods: {
    async gettableData () {
      const { data: res } = await this.$http.get('categories', { params: this.queryInfo })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.tableData = res.data.result
      this.total = res.data.total
    },
    handleSizeChange (val) {
      this.queryInfo.pagesize = val
      this.gettableData()
    },
    handleCurrentChange (val) {
      this.queryInfo.pagenum = val
      this.gettableData()
    },
    async userstatechange (userinfo) {
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
        userinfo.mg_state = !userinfo.mg_state
      } else {
        this.$message.success('修改用户信息成功')
      }
    },
    isCellPhone (val) {
      if (!/^1(3|4|5|6|7|8)\d{9}$/.test(val)) {
        return false
      } else {
        return true
      }
    },
    addDialogClosed (refForm) {
      this.$refs[refForm].resetFields()
    },
    editDialogClosed (refForm) {
      this.$refs[refForm].resetFields()
    },
    setRoleDialogClosed (refForm) {
      this.$refs[refForm].resetFields()
    },
    addCate (refForm) {
      console.log(this.addForm)
      // this.$refs.addFormRef.validate(async valid => {
      //   if (valid) {
      //     const { data: res } = await this.$http.post('users', this.addForm)
      //     console.log(res)
      //     if (res.meta.status !== 201) {
      //       this.$message.error('添加用户失败')
      //     } else {
      //       this.$message.success('添加用户成功')
      //       this.dialogVisible = false
      //       this.gettableData()
      //     }
      //   } else {
      //     return false
      //   }
      // })
    },
    editUser (editFormRef) {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put('users/' + this.editForm.id, {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          })
          console.log(res)
          if (res.meta.status !== 200) {
            this.$message.error(res.meta.msg)
          } else {
            this.$message.success('编辑用户成功')
            this.editdialogVisible = false
            this.gettableData()
          }
        } else {
          return false
        }
      })
    },
    async showeditdialog (id) {
      this.editdialogVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error('查询用户信息失败')
      } else {
        this.editForm = res.data
      }
    },
    open (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('users/' + id)
        console.log(res)
        if (res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
        } else {
          this.gettableData()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async saveRole (refForm) {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色!')
      }
      console.log('this.setRoleForm.id==' + this.setRoleForm.id)
      const { data: res } = await this.$http.put(`users/${this.setRoleForm.id}/role`, {
        rid: this.selectedRoleId
      })
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      } else {
        this.gettableData()
        this.$message({
          type: 'success',
          message: res.meta.msg
        })
        this.setRoledialogVisible = false
      }
    },
    async showsetRoledialog (row) {
      this.setRoledialogVisible = true
      this.setRoleForm.id = row.id
      this.setRoleForm.username = row.username
      this.setRoleForm.role_name = row.role_name
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.roleNameList = res.data
    },
    async getparentCatList () {
      //获取父级分类数据列表
      const { data: res } = await this.$http.get('categories', { params: { type: 2 } })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.parentCatList = res.data
    },
    showdialogVisible () {
      this.dialogVisible = true
      this.getparentCatList()
    },
    handleChange () {
      if (this.selectedKeys.length > 0) {
        this.addForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
        //为当前分类等级赋值
        this.addForm.cat_level = this.selectedKeys.length
        return
      } else {
        //父分类id
        this.addForm.cat_pid = 0
        //为当前分类等级赋值
        this.addForm.cat_level = 0
      }
    }
  }

}
</script>

<style lang="less" scoped>
  .el-breadcrumb {
    margin-bottom: 15px;
    font-size: 12px;
  }

  .el-card {
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15);
  }

  .el-table {
    margin-top: 15px;
    font-size: 12px;
  }

  .el-pagination {
    margin-top: 15px;
  }

  .tree-table1 {
    margin-top: 20px;
  }

  .el-cascader {
    width: 100%;
  }

  .el-cascader-menu {
    height: 300px;
  }

</style>
